import { reqAddMajor, reqUpdateMajor } from "@/api/reqMajor"
import type { Major } from "@/types/major"
import { type FormRules, type FormInstance, ElMessage } from "element-plus"
import { ref, reactive, type Ref } from "vue"

export const useAddAndUpdateMajor = function (changeRef: Ref<symbol>) {
  /* dialog 相关逻辑*/
  const titleRef = ref("")
  const dialogRef = ref(false)
  //   id 在数据库中作为唯一key值，majorname也是唯一
  const majorForm = ref<Major>({ majorname: "" })
  // 添加表单校验
  const formRules = reactive<FormRules<Major>>({
    majorname: [
      { required: true, message: "请输入专业名称", trigger: "blur" },
      {
        pattern: /^[\u4e00-\u9fa5]+$/,
        message: "专业名称只能为汉字",
        trigger: "blur",
      },
    ],
  })
  const formEle = ref<FormInstance>()
  const close = () => {
    // 让弹框消失
    dialogRef.value = false
    // 重置表单内容
    formEle.value?.resetFields()
    majorForm.value = { majorname: "" }
  }

  /* 添加 专业的逻辑 */
  const addMajorHandler = () => {
    // 1. 修改弹窗状态
    dialogRef.value = true
    // 2. 修改title
    titleRef.value = "添加专业"
  }

  //编辑专业
  const updateMajorHandler = (major: Major) => {
    dialogRef.value = true
    titleRef.value = "修改专业"
    majorForm.value = { ...major }
  }
  const updateMajor = () => {
    formEle.value?.validate(async (isOk) => {
      // 发送修改的请求
      if (isOk) {
        const { msg, status } = await reqUpdateMajor(majorForm.value)
        if (status === 0) {
          ElMessage.success("修改成功")
          changeRef.value = Symbol()
          close()
        }
      }
    })
  }

  const addMajor = () => {
    // 表单校验通过
    formEle.value?.validate(async (isOk) => {
      if (isOk) {
        // 发送添加专业的请求
        const { data, msg, status } = await reqAddMajor(majorForm.value)
        if (status === 0) {
          ElMessage.success("添加成功")
          // 需要重新拉取当前数据
          changeRef.value = Symbol()
          close()
        }
      }
    })
  }

  const addOrUpdate = () => {
    if (titleRef.value === "修改专业") {
      updateMajor()

    } else {
      addMajor()
    }
    
  }
  return {
    titleRef,
    dialogRef,
    majorForm,
    formRules,
    formEle,
    close,
    addMajorHandler,
    addMajor,
    updateMajorHandler,
    addOrUpdate,
  }
}
